<template>
  <el-card style="height: 99%" class="card">
    <template #header>
      <div class="card-header">
        <span>用户列表</span>
      </div>
    </template>
    <!-- <VSearch :options="options"></VSearch> -->

    <div>
      <el-form inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.position">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="房客" value="2"></el-option>
            <el-option label="房主" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.sex">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
            <el-option label="保密" value="保密"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status">
            <el-option label="开启" value="1"></el-option>
            <el-option label="关闭" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            type="datetimerange"
            v-model="searchForm.createTime"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div
        style="
          width: 100%;
          padding-bottom: 20px;
          display: flex;
          justify-content: flex-end;
        "
      >
        <el-button type="primary" @click="searchSubmit">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>
    <!-- <el-scrollbar height="600px"> -->
    <VTable
      :tableData="tableData"
      :options="options"
      @getSelection="handleSelection"
    >
      <template #menubtn>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="warning" @click="handleBatchDelete"
          >批量删除</el-button
        >
      </template>

      <template #operate="scope">
        <el-button
          size="small"
          link
          type="primary"
          :icon="View"
          @click="handleDetail(scope.row)"
          >查看</el-button
        >
        <el-button
          size="small"
          link
          type="primary"
          :icon="Edit"
          @click="handleEdit(scope.row)"
          >编辑</el-button
        >
        <el-button
          size="small"
          link
          type="danger"
          :icon="Delete"
          @click="handleDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </VTable>
    <!-- </el-scrollbar> -->

    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <!-- 编辑/新增 -->
      <el-form
        v-if="actionType === '新增' || actionType === '编辑'"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item
          v-for="item in filterOptions"
          :key="item"
          :label="item.label"
          :prop="item.prop"
        >
          <el-select
            v-if="item.type === 'select'"
            v-model="ruleForm[item.prop]"
          >
            <el-option
              v-for="i in item.options"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>

          <el-input-number
            v-if="item.type === 'number'"
            v-model="ruleForm[item.prop]"
          ></el-input-number>

          <el-upload
            v-if="item.type === 'image'"
            action="#"
            :auto-upload="false"
            :multiple="false"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="uploadImage"
            ><el-icon
              v-if="imageUrl"
              class="el-icon-circle-close deleteImg"
              @click.stop="handleRemove"
              ><Close
            /></el-icon>
            <div class="imgBox">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" /><el-icon
                v-else
                class="avatar-uploader-icon"
                ><Plus
              /></el-icon>
            </div>
          </el-upload>
          <el-dialog v-model="dialogVisibleImg">
            <img
              w-full
              :src="dialogImageUrl"
              alt="Preview Image"
              style="width: 200px; height: 200px"
            />
          </el-dialog>

          <el-input v-if="!item.type" v-model="ruleForm[item.prop]"></el-input>
        </el-form-item>
      </el-form>

      <!-- 详情 -->
      <Description
        v-if="actionType === '查看'"
        :options="options"
        :dataItem="dataItem"
      >
      </Description>

      <template #footer>
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          @click="resetForm(ruleFormRef)"
          >关闭</el-button
        >
        <el-button v-if="actionType === '查看'" @click="dialogVisible = false"
          >关闭</el-button
        >
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          type="primary"
          @click="submitForm(ruleForm)"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadFile,
} from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import VTable from "../../components/VTable/index.vue";
import Description from "../../components/Description/index.vue";
// import VSearch from "../../components/VSearch/index.vue";

import { Delete, Edit, View, Plus, Close } from "@element-plus/icons-vue";

import {
  getUserList,
  addUser,
  editUser,
  deleteUser,
  batchDeleteUser,
  searchUser,
} from "../../api/userManage/index";
import { Loading } from "element-plus/es/components/loading/src/service";

const tableData = ref<any>([]);
const options = [
  {
    prop: "username",
    label: "用户名",
    isTable: true,
    isForm: true,
    width: 80,
    isSearch: true,
  },
  {
    prop: "password",
    label: "密码",
    isTable: false,
    isForm: true,
  },
  {
    prop: "position",
    label: "角色",
    isTable: true,
    isForm: true,
    type: "select",
    options: [
      { value: 1, label: "管理员" },
      { value: 2, label: "房客" },
      { value: 3, label: "房主" },
    ],
    isSearch: true,
  },
  {
    prop: "avator",
    label: "头像",
    isTable: true,
    isForm: true,
    type: "image",
  },
  {
    prop: "sex",
    label: "性别",
    isTable: true,
    isForm: true,
    type: "select",
    options: [
      { value: "男", label: "男" },
      { value: "女", label: "女" },
      { value: "保密", label: "保密" },
    ],
    isSearch: true,
  },
  {
    prop: "status",
    label: "状态",
    isTable: true,
    isForm: true,
    type: "select",
    options: [
      { value: 1, label: "开启" },
      { value: 2, label: "关闭" },
    ],
    isSearch: true,
  },
  {
    prop: "createTime",
    label: "创建时间",
    isTable: false,
    isForm: false,
    isSearch: true,
    type: "datetimerange",
  },
  
];
const filterOptions = options.filter((item) => item.isForm == true);

const searchForm = ref<any>({
  username: "",
  position: "",
  sex: "",
  status: "",
  createTime: Date,
});

const validateUsername = () => {};
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
});
let ruleForm = reactive({
  username: "",
  password: "",
  position: "",
  avator: "",
  sex: "",
  status: 0,
});
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};

const dialogTitle = ref("查看"); // 弹出层标题
const actionType = ref(""); // 操作按钮的类型
const setDialogTile = (type: string) => {
  dialogTitle.value = type;
  actionType.value = type;
  dialogVisible.value = true;
};

const dialogVisible = ref<boolean>(false);
const dataItem = ref<object>({});

// 详情
const handleDetail = (scope: any) => {
  dataItem.value = scope;
  setDialogTile("查看");
};
// 编辑
const handleEdit = async (scope: any) => {
  ruleForm = scope;
  imageUrl.value = "http://127.0.0.1:8090/public/avator/" + ruleForm.avator;
  setDialogTile("编辑");
};
//新增
const handleAdd = () => {
  ruleForm = reactive({
    username: "",
    password: "",
    position: "",
    avator: "",
    sex: "",
    status: 1,
  });
  imageUrl.value = "";
  setDialogTile("新增");
};
//删除
const handleDelete = async (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(id);
      const res = await deleteUser(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//子组件传值--多选
const ids = ref<any>([]);
const handleSelection = (val: any) => {
  // console.log("子组件传值：", val);
  const selecction: any = [];
  val.forEach((item: any) => {
    selecction.push(item.id);
  });
  ids.value = selecction;
  console.log("ids.value:", ids.value);
};
// 批量删除
const handleBatchDelete = async () => {
  if (ids.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择数据",
    });
    return;
  }
  ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await batchDeleteUser(ids.value);
      if (res.data.success) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//上传
// const imageUrl = ref("");
// const handleAvatarSuccess: UploadProps["onSuccess"] = (
//   response,
//   uploadFile
// ) => {
//   imageUrl.value = URL.createObjectURL(uploadFile.raw!);
//   console.log("imageUrl.value:", imageUrl.value);
// };
// const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
//   if (rawFile.type !== "image/jpeg") {
//     ElMessage.error("必须是jpg类型!");
//     return false;
//   } else if (rawFile.size / 1024 / 1024 > 2) {
//     ElMessage.error("不能大于2mb!");
//     return false;
//   }
//   return true;
// };
// const imgVisible = ref<boolean>(true);
const dialogImageUrl = ref("");
const dialogVisibleImg = ref(false);
const disabled = ref(false);
const fileVisible = ref<boolean>(true);

const imageUrl = ref();
const imgRaw = ref();
const uploadImage = (item: any) => {
  console.log("item", item);

  console.log(item.raw);
  imgRaw.value = item;
  imageUrl.value = URL.createObjectURL(item.raw); // 图片上传浏览器回显地址
  const file = imgRaw.value.raw;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = async () => {
    // console.log("转base64结果：", reader.result);
    ruleForm.avator = reader.result;
  };
  reader.onerror = (error) => {
    console.log("error", error);
  };
};
const handleRemove = () => {
  imageUrl.value = "";
};

// const handleRemove = (file: UploadFile) => {
//   console.log(file);
//   fileVisible.value = false;
// };

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisibleImg.value = true;
};

const handleDownload = (file: UploadFile) => {
  console.log(file);
};
const update = (e) => {
  console.log(e.raw);
  const file = e.raw;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    // console.log("转base64结果：", reader.result);
    ruleForm.avator = reader.result;
    // console.log("转base64结果：", ruleForm.avator);
    console.log(ruleForm);
  };
  reader.onerror = (error) => {
    console.log("error", error);
  };
};

const handleCancel = (file: UploadFile) => {
  file.url = "";
};

//搜索
const searchSubmit = async () => {
  const res = await searchUser(searchForm.value);
  tableData.value = res.data.data;
};
//重置搜索
const resetSearch = async () => {
  searchForm.value = {
    username: "",
    position: "",
    sex: "",
    status: "",
  };
  await onLoad();
};
//提交
const submitForm = async (ruleForm) => {
  if (actionType.value === "新增") {
    const res = await addUser(ruleForm);
    if (res.data.success) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
      await onLoad();
    } else {
      ElMessage.error(res.data.msg);
    }
  } else if (actionType.value === "编辑") {
    console.log(ruleForm);
    // return;
    const res = await editUser(ruleForm);
    if (res.data.success == true) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  }

  onLoad();
  dialogVisible.value = false;
};

const onLoad = async () => {
  const res = await getUserList();

  tableData.value = res.data.data;
};

onMounted(async () => {
  await onLoad();
  console.log(tableData.value);
});
</script>

<style scoped lang="scss">
// .card {
//   overflow-y: auto; /* 开启滚动显示溢出内容 */
// }
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.deleteImg {
  font-size: 20px;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
}
</style>
